package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.Dto.OrderDTO;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Yan
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Override
    public Result<String> submit(Orders orders) {
        //参数校验
        if(ObjectUtils.isEmpty(orders)){
            return Result.error("参数错误");
        }

        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);

        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);

        if (shoppingCarts == null ||shoppingCarts.size() == 0){
            return Result.error("购物车是空,不能下单");
        }

        //查询用户数据
        User user =userService.getById(userId);

        //查询地址数据
        LambdaQueryWrapper<AddressBook> wrapper1 =new LambdaQueryWrapper<>();
        wrapper1.eq(AddressBook::getId,orders.getAddressBookId());
        wrapper1.eq(AddressBook::getUserId,userId);

        AddressBook addressBook = addressBookService.getOne(wrapper1);
        if (ObjectUtils.isEmpty(addressBook)){
            return Result.error("用户地址信息有误");
        }
        //订单号
        //AtomicInteger amount = new AtomicInteger(0);

        //设置订单号
        //使用雪花算法：MP提供
        long orderId = IdWorker.getId();
        //获取购物车的数据
        //订单明细信息
        //List<OrderDetail> orderDetails =shoppingCarts.stream().map()

        List<OrderDetail> orderDetailList =new ArrayList<>();

        BigDecimal total = new BigDecimal(0);

        //把购物车的数据封装给订单明细
        for (ShoppingCart shoppingCart : shoppingCarts) {
            //单价
            BigDecimal amount = shoppingCart.getAmount();
            //数量
            Integer number = shoppingCart.getNumber();

            //单个菜品套餐总价
            BigDecimal totalPrice = amount.multiply(new BigDecimal(number));
            total = total.add(totalPrice);

            OrderDetail orderDetail =new OrderDetail();
            //拷贝购物车明细到订单明细
            BeanUtils.copyProperties(shoppingCart,orderDetail);

            //设置订单号
            orderDetail.setOrderId(orderId);
            orderDetailList.add(orderDetail);
        }

        //完善订单数据
        //未付款
        orders.setStatus(2);
        //用户id
        orders.setUserId(userId);
        //用户名
        orders.setUserName(user.getName());
        //手机号
        orders.setPhone(user.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setOrderTime(LocalDateTime.now());
        orders.setConsignee(addressBook.getConsignee());
        orders.setCheckoutTime(LocalDateTime.now());
        //订单号
        orders.setNumber(String.valueOf(orderId));
        //设置签名


        //总金额
        orders.setAmount(total);

        //1.保存订单表数据
        this.save(orders);

        //2.保存订单明细表
        orderDetailService.saveBatch(orderDetailList);
        //清空购物车
        shoppingCartService.remove(wrapper);

        return Result.success("下单成功");
    }

    /**
     * 分页查询
     * 最新订单，历史订单
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Result<Page<OrderDTO>> findOrderByPage(Long page, Long pageSize) {

        if (ObjectUtils.isEmpty(page)||page<=0){
            page = 1L;
        }
        if (ObjectUtils.isEmpty(pageSize)||pageSize<=0){
            pageSize = 1L;
        }

        LambdaQueryWrapper<Orders> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId,BaseContext.getCurrentId());
        wrapper.orderByDesc(Orders::getOrderTime);
        Page<Orders> pageOrder = new Page<>(page,pageSize);

        this.page(pageOrder,wrapper);

        List<Orders> records = pageOrder.getRecords();
        //创建DTO集合
        List<OrderDTO> orderDTOs =new ArrayList<>();


        for (Orders record : records) {
            OrderDTO orderDTO =new OrderDTO();
            BeanUtils.copyProperties(record,orderDTO);
            //根据orderId,Orders中的number查询明细表
            String number = record.getNumber();
            LambdaQueryWrapper<OrderDetail> wrapperOrderDetail =new LambdaQueryWrapper<>();
            wrapperOrderDetail.eq(OrderDetail::getOrderId,number);
            List<OrderDetail> list = orderDetailService.list(wrapperOrderDetail);
            orderDTO.setOrderDetails(list);
            orderDTOs.add(orderDTO);
        }



        Page<OrderDTO> result = new Page<>();
        BeanUtils.copyProperties(pageOrder,result);
        result.setRecords(orderDTOs);

        return Result.success(result);
    }

    @Override
    public Result<Page<Orders>> findByPage(Long page, Long pageSize, Long number, Date beginTime, Date endTime) {

        log.info("开始时间-----------------------------------{}",beginTime);
        log.info("结束时间-----------------------------------{}",endTime);

        if (ObjectUtils.isEmpty(page)||page<=0){
            page = 1L;
        }
        if (ObjectUtils.isEmpty(pageSize)||pageSize<=0){
            pageSize = 10L;
        }

        Page<Orders> ordersPage =new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> wrapper =new LambdaQueryWrapper<>();
        wrapper.like(ObjectUtils.isNotEmpty(number),Orders::getNumber,number);

        wrapper.ge(ObjectUtils.isNotEmpty(beginTime),Orders::getOrderTime,beginTime);
        wrapper.le(ObjectUtils.isNotEmpty(endTime),Orders::getOrderTime,endTime);

        this.page(ordersPage,wrapper);

        return Result.success(ordersPage);
    }
}